package com.dyy.AI_System.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * Spring Security配置类
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
            throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    /**
     * 安全过滤链配置
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // 禁用CSRF（跨站请求伪造防护），适用于API服务
            .csrf(AbstractHttpConfigurer::disable)
            
            // 禁用默认的表单登录
            .formLogin(AbstractHttpConfigurer::disable)
            
            // 禁用HTTP基本认证
            .httpBasic(AbstractHttpConfigurer::disable)
            
            // 配置HTTP请求的授权规则
            .authorizeHttpRequests(authorize -> authorize
                // 允许所有用户访问Swagger文档相关的API
                .requestMatchers("/doc.html", "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**").permitAll()
                
                // 允许登录请求无需认证
                .requestMatchers("/api/login").permitAll()
                
                // 允许用户相关的公开API
                .requestMatchers("/users/**").permitAll()
                
                // 其他所有请求都需要认证
                .anyRequest().authenticated()
            );

        return http.build();
    }
}